package cn.m3a1.control;

import cn.m3a1.bean.Msg;
import cn.m3a1.bean.User;
import cn.m3a1.service.LoginService;
import cn.m3a1.util.GlobalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author wyj
 * @date 2019/6/28
 * @time 下午1:20
 */
@Controller
@RequestMapping("/login")
public class LoginControl {
    @Autowired
    LoginService loginService;

    @RequestMapping("/myindex")
    public String myindex(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "login.html";
        }
       return  "redirect:/login/checkJump";
    }

    /**
     * 登录验证，返回json数据
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Msg login(HttpServletRequest request, User user) {
        if (GlobalUtils.isEmpty(user.getUsername()) || GlobalUtils.isEmpty(user.getPassword())) {
            return Msg.fail().add("msg", "用户名或密码不能为空");
        }
        user.setPassword(GlobalUtils.md5Encode(user.getPassword()));
        // System.out.println(user.getUsername()+user.getPassword());
        List<User> users = loginService.getCheckLogin(user);
        Boolean checkLogin = users.size() == 1;
        if (checkLogin) {
            //如果登录成功，将用户名信息存入session中
            request.getSession().setAttribute("loginUser", users.get(0));
            return Msg.success();
        } else {
            return Msg.fail().add("msg", "用户名或密码错误");
        }

    }

    @RequestMapping("/checkJump")
    public String checkJump(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/";
        }
        int type = loginUser.getType();
        if (type == 1) {
            return "redirect:/student/stuReqForm";
        } else if (type == 50) {
            return "redirect:/teacher/teaCouse";
        } else if (type == 70) {
            return "redirect:/head/home";
        } else if (type == 99) {
            return "redirect:/admin/home";
        }

        return null;
    }
    @RequestMapping("/loginout")
    public  String loginout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("loginUser");
        return "redirect:/login/myindex";
    }
}
